#include <ftp_file.h>

#include <AsyncLogger.h>
#include <fmt/format.h>
#include <sstream>
#include <chrono>
#include <array>

FTPFile::FTPFile():
	filename_(""),
	offset_(0),
	fileSize_(0),
	file_(nullptr)
{}

bool FTPFile::open(const std::string& file, const std::string& mode)
{
	filename_ = file;
	file_ = ::fopen(filename_.c_str(), mode.c_str());
	if (file_ == nullptr) {
		perror("fopen");
		return false;
	}
	if (FTPUtil::exist(file)) {
		fileSize_ = std::filesystem::file_size(file);
	}
	// 设置偏移量，用于断点重传
	int res = std::fseek(file_, offset_, SEEK_SET) == 0;
	return res;
}

bool FTPFile::close()
{
	if (file_ != nullptr) {
		std::fflush(file_);
		std::fclose(file_);
	}
	file_ = nullptr;
	offset_ = 0;
	fileSize_ = 0;
	filename_ = "";
	return true;
}

int FTPFile::read(char* readBuf, size_t size)
{
	size_t n = std::fread(readBuf, sizeof(char), size, file_);
	offset_ += n;
	return n;
}

int FTPFile::write(const char* writeBuf, size_t size)
{
	size_t n = std::fwrite(writeBuf, sizeof(char), size, file_);
	offset_ += n;
	return n;
}

FTPFile::~FTPFile()
{
	close();
}

std::string FTPFile::getFilename()
{
	return std::filesystem::path(filename_).filename().string();
}
